<template>
  <biz-wrap-simple :is-empty-container="forceEmptyWrap || idxRoute.length !== 0">
    <!-- grid-layout -->
    <!-- :style="curRowStyle" -->
    <gd-row
      v-model:layout="curLevelGridLayoutBinding"
      :margin="[0, 0]"
      v-bind="getRowProps(pageTemplateLayoutConfigInfo.rowConfig)"
      :is-wrapped-by-grid-layout="proxyIsDesignerLayoutCanvas"
      :style="curRowStyle"
      v-if="isRefreshLayout"
      class="biz-grid-layout-simple-container"
    >
      <template #default="rowSlotProps">
        <template v-if="pageTemplateLayoutConfigInfo.allColConfigs.length > 1">
          <template v-for="(item, idx) in pageTemplateLayoutConfigInfo.allColConfigs" :key="idx">
            <!-- grid-item -->
            <gd-col
              v-bind="getColProps(item, idx, rowSlotProps)"
              :is-wrapped-by-grid-layout="proxyIsDesignerLayoutCanvas"
              :grid-layout-config="getGridLayoutConfig(idx)"
              @resize-item="onResizeItem"
              :style="getColStyle({ colItem: item })"
            >
              <template v-if="item._slotCrudCompId">
                <biz-dynmic-comp-simple
                  :name="getTemplateName(item._slotCrudCompId)"
                  :template-idx="getTemplateConfigIdx(item._slotCrudCompId)"
                  :is-designer-layout-canvas="proxyIsDesignerLayoutCanvas"
                  :static-resource="staticResource"
                  :static-meta-configs="getCurTemplateStaticMetaConfig(item._slotCrudCompId)"
                  @biz-designer-layout-bizcomp:blank:cmd="(cmd) => blankLayout_doItemStrategy({ cmd, idx })"
                ></biz-dynmic-comp-simple>
              </template>
              <!-- grid-layout -->
              <biz-grid-layout-simple
                v-else
                v-bind="getRecursionProps(idx)"
                :isDesignerLayoutCanvas="proxyIsDesignerLayoutCanvas"
                @biz-grid-layout:item:cmd="doItemStrategy"
                @biz-grid-layout:resize-layout="onResizeItem"
              ></biz-grid-layout-simple>
            </gd-col>
          </template>
        </template>
        <!-- grid-item -->
        <gd-col
          v-else-if="pageTemplateLayoutConfigInfo.allColConfigs.length === 1"
          v-bind="getColProps(colConfig, 0, rowSlotProps)"
          :is-wrapped-by-grid-layout="proxyIsDesignerLayoutCanvas"
          :grid-layout-config="getGridLayoutConfig(0)"
          @resize-item="onResizeItem"
          :style="getColStyle({ colItem: pageTemplateLayoutConfigInfo.allColConfigs[0] })"
        >
          <!-- grid-layout -->
          <template v-if="getColItemContentType(colConfig) === 'GridContainerComp'">
            <biz-grid-layout-simple
              v-bind="getRecursionProps(0)"
              :isDesignerLayoutCanvas="proxyIsDesignerLayoutCanvas"
              @biz-grid-layout:item:cmd="doItemStrategy"
              @biz-grid-layout:resize-layout="onResizeItem"
            ></biz-grid-layout-simple>
          </template>
          <template v-else-if="colConfig._slotCrudCompId">
            <biz-dynmic-comp-simple
              :name="getTemplateName(colConfig._slotCrudCompId)"
              :template-idx="getTemplateConfigIdx(colConfig._slotCrudCompId)"
              :is-designer-layout-canvas="isDesignerLayoutCanvas"
              :static-resource="staticResource"
              :static-meta-configs="getCurTemplateStaticMetaConfig(item._slotCrudCompId)"
              @biz-designer-layout-bizcomp:blank:cmd="(cmd) => blankLayout_doItemStrategy({ cmd, idx: 0 })"
            ></biz-dynmic-comp-simple>
          </template>
          <!-- 兼容单CRUD组件页面 -->
          <biz-dynmic-comp-simple
            v-else
            name="BizSearchformTablelistSimple"
            :template-idx="0"
            :is-designer-layout-canvas="isDesignerLayoutCanvas"
            :static-resource="staticResource"
            :static-meta-configs="getCurTemplateStaticMetaConfig(item._slotCrudCompId)"
            @biz-designer-layout-bizcomp:blank:cmd="(cmd) => blankLayout_doItemStrategy({ cmd, idx: 0 })"
          ></biz-dynmic-comp-simple>
          <!-- <biz-searchform-tablelist-simple v-else :template-idx="getTemplateConfigIdx(colConfig._slotCrudCompId)">
            </biz-searchform-tablelist-simple> -->
        </gd-col>
      </template>
    </gd-row>
  </biz-wrap-simple>
</template>
<script>
  export default {
    name: "BizGridLayoutSimple",
    inheritAttrs: false,
  };
</script>
<script setup>
  import { computed, useAttrs, toRaw, toRef, watch, watchEffect, ref, onBeforeUnmount } from "vue";
  import buildInBizTemplateProps from "@gd-accbuild-core/hooks/buildInBizTemplateProps";
  import { getPageTemplateLayoutConfigInfo } from "@gd-accbuild-core/hooks/useGetCurUiTemplateInfo/utils/getPageUiTemplateMetaListAndData";
  import { useStore } from "@gd-accbuild-core/store/hackVueStore";
  // #ifdef H5
  import { hackFixH5AdressBar } from "@gd-accbuild-core/pages/hooks/hackFixPageNotFound";
  // #endif
  import { debounce, throttle } from "@gd-accbuild-core/config/utils";
  const props = defineProps({
    ...buildInBizTemplateProps,
    idxRoute: {
      type: Array,
      default: () => [],
    },
    forceEmptyWrap: {
      type: Boolean,
      default: false,
    },
    /////////////////
    //是否用于设计器布局渲染
    isDesignerLayoutCanvas: {
      type: Boolean,
      default: false,
    },
    curHighLightColId: {
      type: Number,
    },
  });

  const _store = useStore();
  // #ifdef H5
  watchEffect(() => {
    const isDesignerLayoutCanvas = props.isDesignerLayoutCanvas;
    const idxRoute = props.idxRoute;
    if (idxRoute.length === 0 && !isDesignerLayoutCanvas) {
      hackFixH5AdressBar(_store);
    }
  });
  // #endif
  const isUseStaticResource = computed(() => {
    const staticResource = props.staticResource;
    return staticResource && Object.keys(staticResource).length > 0;
  });
  /**
   * 获取当前页面的资源
   */
  const useGetCurPageResource = ({ isUseStaticResource = false, staticResource = {} }) => {
    const store = _store;
    return isUseStaticResource ? staticResource : store.state.permission.curPageInfo.resource;
  };
  const curPageResource = useGetCurPageResource({
    isUseStaticResource: isUseStaticResource.value,
    staticResource: props.staticResource,
  });
  const pageTemplateLayoutConfigInfo = computed(() =>
    getPageTemplateLayoutConfigInfo({
      resource: curPageResource,
      idxRoute: props.idxRoute,
    })
  );

  /* console.log(
  curPageResource,
  props.idxRoute,
  props,
  "--------启动---------",
  pageTemplateLayoutConfigInfo.value
); */
  const colConfig = pageTemplateLayoutConfigInfo.value.allColConfigs[0];
  //
  const isUseGridLayout = true;
  const proxyIsDesignerLayoutCanvas = computed(() => {
    return props.isDesignerLayoutCanvas && isUseGridLayout;
  });
  const getColProps = (colConfig, idx, rowSlotProps) => {
    let ret = {};
    if (proxyIsDesignerLayoutCanvas.value) {
      ret = rowSlotProps?.gridItemProps ?? {};
    } else {
      Object.keys(colConfig).forEach((key) => {
        if (!key.startsWith("_") && key !== "rowConfig" && key !== "allColConfigs") {
          ret[key] = colConfig[key];
        }
      });
    }
    ret["idxRoute"] = props.idxRoute;
    return ret;
  };
  const getGridLayoutConfig = computed(() => {
    return (idx) => {
      return curLevelGridLayoutBinding.value[idx];
    };
  });
  const getRowProps = (rowConfig) => {
    if (proxyIsDesignerLayoutCanvas.value) {
      return {
        "col-num": 24,
        "row-height": 24,
        style: rowConfig.style,
      };
    } else {
      return rowConfig;
    }
  };
  const layoutItemIdSplitStr = "9999";
  const getPrefixId = (idxRoute = []) => {
    return (
      idxRoute
        .map((e) => {
          return typeof e !== "number" ? 0 : e;
        })
        .join("") + layoutItemIdSplitStr
    );
  };
  const curHighLightColId = toRef(props, "curHighLightColId");
  const curLevelGridLayoutBinding = computed({
    get: () => {
      const allColConfigs = pageTemplateLayoutConfigInfo.value.allColConfigs;
      if (allColConfigs.length >= 1) {
        const prefixId = getPrefixId(props.idxRoute);
        const rr = [];
        let offsetX = 0;
        let cacheX = 0;
        let cacheY = 0;
        allColConfigs.forEach((colConfig, idx) => {
          const overSpan = cacheX + colConfig.span - 24;
          if (overSpan >= 0 || idx === 0) {
            cacheX = 0;
          } else {
            cacheX += allColConfigs[idx - 1].span; //colConfig.span;
          }
          if (overSpan >= 0) {
          }
          const contentType = getColItemContentType(colConfig);
          if (contentType === "GridContainerComp") {
            /* rr.push({
              x: cacheX,
              y: cacheY,
              w: colConfig.span,
              h: 24,
              i: +(prefixId + idx),
            }); */
          } else {
            const id = +(prefixId + idx); //169 / c=24/x
            //TODO:FIXME: 暂时为满足小地图 576
            const hh = Math.floor((24 / 576) * +colConfig.style.height.replace("px", ""));
            //console.log(colConfig.style.height, "高度==");
            //const hh = 24 / (169 / +colConfig.style.height.replace("px", ""));
            rr.push({
              x: cacheX,
              y: cacheY,
              w: colConfig.span,
              h: hh,
              i: id,
              idx: idx,
              isHighLight: curHighLightColId.value === id,
              highLightIdRef: curHighLightColId,
            });
          }
        });
        return rr;
      } else {
        return [];
      }
    },
    set: (v) => {
      //console.log(v, "====xxxxxx");
      return v;
    },
  });
  //////////////////

  /////////////////
  const _emits = defineEmits(["biz-grid-layout:resize-layout", "biz-grid-layout:item:cmd"]);
  const isRefreshLayout = ref(true);
  //
  const useMouseDown = () => {
    let isMouseDown = ref(0);
    // #ifdef H5
    if (process.env.PUBLIC_TARGET === "Designer") {
      const mouseDownEvent = () => {
        ++isMouseDown.value;
        // setTimeout(() => {
        //   console.log("鼠标按下", isMouseDown.value);
        // }, 300);
      };
      document.body.addEventListener("mousedown", mouseDownEvent);
      const mouseUpEvent = () => {
        --isMouseDown.value;
        // setTimeout(() => {
        //   console.log("鼠标抬起", isMouseDown.value);
        // }, 300);
      };
      document.body.addEventListener("mouseup", mouseUpEvent);
      onBeforeUnmount(() => {
        document.body.removeEventListener("mousedown", mouseDownEvent);
        document.body.removeEventListener("mouseup", mouseUpEvent);
      });
    }
    // #endif
    return { isMouseDown: isMouseDown };
  };
  const { isMouseDown } = useMouseDown();
  //
  const onResizeItem = (params) => {
    let curRowIdx = 0;
    let curColIdx = 0;
    const appendParams = {};
    if (props.idxRoute.length === 2) {
      appendParams.idxRoute = [...props.idxRoute];
    } else {
      const ret = { ...params.params };
      const cacheIdxRoute = [...params.idxRoute];
      params = ret;
      const ii = (params.i + "").indexOf(layoutItemIdSplitStr);
      const curI = +(params.i + "").substring(ii + layoutItemIdSplitStr.length);
      const layoutInfo = getPageTemplateLayoutConfigInfo({
        resource: curPageResource,
        idxRoute: cacheIdxRoute,
      });
      curColIdx = layoutInfo.allColConfigs.findIndex((el, idx) => idx === curI);
      curRowIdx = cacheIdxRoute[1];
      appendParams.curColIdx = curColIdx;
      appendParams.curRowIdx = curRowIdx;
    }
    const func = () => {
      _emits("biz-grid-layout:resize-layout", {
        staticResource: props.staticResource,
        params: { ...params },
        ...appendParams,
      });
    };
    const timer = setInterval(() => {
      if (isMouseDown.value) {
        return;
      }
      clearInterval(timer);
      setTimeout(func, 500);
    }, 300);
  };
  const _attrs = useAttrs();
  const cacheRowSpace = computed(() => {
    return _attrs?.cacheRowSpace ?? { cssVal: 0, num: 0 };
  });
  const doItemStrategy = ({ params, cmd }) => {
    const appendParams = {};
    if (!params.hasOwnProperty("cacheRowSpace")) {
      appendParams["cacheRowSpace"] = cacheRowSpace.value.num;
    }
    if (!params.hasOwnProperty("absoluteHeigh")) {
      appendParams["absoluteHeigh"] = pageTemplateLayoutConfigInfo.value.rowConfig.style.height;
    }
    _emits(`biz-grid-layout:item:cmd`, { cmd, params: { ...params, ...appendParams } });
  };
  const blankLayout_doItemStrategy = ({ cmd, idx }) => {
    const v = getGridLayoutConfig.value(idx);
    const params = {
      span: v.w,
      colIdx: v.idx,
      rowIdx: props.idxRoute.slice(1)[0],
      id: v.i,
    };
    doItemStrategy({ params, cmd });
  };

  const pageUiTemplateConfigs = curPageResource["uiOptions"]["pageUiTemplateConfigs"] ?? [];

  const getTemplateConfigIdx = (templateId) => {
    let templateConfigIdx = pageUiTemplateConfigs.findIndex((el) => el.templateId === templateId);
    return templateConfigIdx !== -1 ? templateConfigIdx : 0;
  };
  const getTemplateName = (templateId) => {
    const templateConfigIdx = getTemplateConfigIdx(templateId);
    return pageUiTemplateConfigs[templateConfigIdx]?.templateName ?? "";
  };

  /////////////最大支持两层,curRow的宽度根据上层(顶层)的宽度计算
  const topLevelStyle = computed(() => {
    return _attrs?.topLevelStyle ?? pageTemplateLayoutConfigInfo.value.rowConfig.style;
  });
  const curRowStyle = computed(() => {
    if (props.idxRoute.length === 0) {
      return topLevelStyle.value;
    } else {
      const style = { ...pageTemplateLayoutConfigInfo.value.rowConfig.style };
      style.width = `calc(${topLevelStyle.value.width} / 24 * ${pageTemplateLayoutConfigInfo.value.span})`;
      return style;
    }
  });
  ///
  const getColStyle = ({ colItem }) => {
    const style = { ...colItem.style };
    return style;
  };
  const DefaultGridGap = "10";
  const getCacheRowSpace = (index) => {
    let c = "";
    let num = 0;
    pageTemplateLayoutConfigInfo.value.allColConfigs
      .filter((el, idx) => index > idx)
      .map((el) => el.rowConfig.style.height)
      .forEach((el, idx) => {
        if (idx === 0) {
          c += el;
          num += +el.replace("px", "");
        } else {
          c += ` + ${el}`;
          num += +el.replace("px", "");
        }
      });
    return {
      cssVal: c ? `calc(${c})` : 0,
      num,
    };
  };
  /////////////
  const getRecursionProps = (index) => {
    const ret = {};
    Object.keys(props).forEach((key) => {
      if (key !== "idxRoute") {
        ret[key] = toRaw(props[key]);
      }
    });
    const curIdxRoute = ["allColConfigs", index];
    ret["idxRoute"] = Array.isArray(props["idxRoute"]) ? [...toRaw(props["idxRoute"]), ...curIdxRoute] : curIdxRoute;
    ret["topLevelStyle"] = topLevelStyle.value;
    ret["cacheRowSpace"] = getCacheRowSpace(index);
    return ret;
  };

  const getColItemContentType = (colItemConfig) => {
    const ColContentType = ["GridContainerComp", "BizComp"];
    const isGridContainerComp =
      colItemConfig.hasOwnProperty("rowConfig") && colItemConfig.hasOwnProperty("allColConfigs");
    return isGridContainerComp ? "GridContainerComp" : "BizComp";
  };

  const getCurTemplateStaticMetaConfig = (templateIdx) => {
    return props.staticMetaConfigs.length >= templateIdx + 1 ? [props.staticMetaConfigs[templateIdx]] : [];
  };
</script>
<style scoped lang="scss">
  :deep(.biz-grid-layout-simple-container.grid-layout-container .vue-grid-layout) {
    margin-top: v-bind("cacheRowSpace.cssVal");
  }
</style>
